import type { InlineEditor } from './inlineEditor';

export function createImage(src: string): Node {
	return (
		<>
			<div>
				<img src={src} style={{ maxWidth: '100%' }} alt="" />
			</div>
			<p></p>
		</>
	);
}

function replaceToParagraph(div: HTMLElement, range: Range) {
	range.setStartAfter(div);
	range.collapse(true);
	const p = (
		<p>
			<br />
		</p>
	);
	range.insertNode(p);
	range.selectNode(div);
	range.deleteContents();
	range.selectNodeContents(p);
	range.collapse(true);
}

function isEmpty(div: Element): boolean {
	const children = Array.from(div.childNodes).filter(
		(c) => !(c.nodeName === '#text' && c.textContent === ''),
	);
	return children.length === 0;
}

export function imageOnKeyDown(editor: InlineEditor, div: HTMLElement, evt: KeyboardEvent) {
	if (evt.key === 'Enter' && !evt.shiftKey) {
		evt.preventDefault();
		const sel = window.getSelection();
		if (!sel || sel.rangeCount === 0) return;
		const range = sel.getRangeAt(0);
		if (!range.collapsed) {
			range.deleteContents();
			range.collapse(true);
		}
		if (isEmpty(div)) {
			replaceToParagraph(div, range);
			editor.emitChange();
			return;
		}
		if (range.startOffset === 0) {
			range.setStartBefore(div);
			range.collapse(true);
			const newp = (
				<p>
					<br />
				</p>
			);
			range.insertNode(newp);
			range.selectNodeContents(div);
			range.collapse(true);
		} else {
			range.setStartAfter(div);
			range.collapse(true);
			const newp = (
				<p>
					<br />
				</p>
			);
			range.insertNode(newp);
			range.selectNodeContents(newp);
			range.collapse(true);
		}
		editor.emitChange();
	} else if (evt.key === 'Backspace') {
		evt.preventDefault();
		const sel = window.getSelection();
		if (!sel || sel.rangeCount === 0) return;
		const range = sel.getRangeAt(0);
		if (!range.collapsed) {
			// range.deleteContents();
			// range.collapse(true);
			replaceToParagraph(div, range);
			editor.emitChange();
		} else {
			if (range.startOffset === 0) {
				// evt.preventDefault();
				if (div.previousElementSibling) {
					if (div.previousElementSibling.nodeName !== 'P') {
						range.selectNode(div.previousElementSibling);
						range.deleteContents();
					} else {
						if (div.previousElementSibling.textContent === '') {
							range.selectNode(div.previousElementSibling);
							range.deleteContents();
						} else {
							range.selectNodeContents(div.previousElementSibling);
							range.collapse(false);
						}
					}
					editor.emitChange();
				}
			} else {
				// evt.preventDefault();
				const previouse = div.previousElementSibling ?? div.nextElementSibling;
				if (previouse) {
					range.selectNode(div);
					range.deleteContents();
					range.selectNodeContents(previouse);
					range.collapse(false);
				} else {
					replaceToParagraph(div, range);
				}
				editor.emitChange();
			}
		}
	} else if (/^(ArrowLeft|ArrowRight|ArrowUp|ArrowDown|Tab)$/.test(evt.key)) {
		// allow
	} else {
		evt.preventDefault();
	}
}
